package com.keyancompany.zhongbaopingtai.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.ChatFriendActivity;
import com.keyancompany.zhongbaopingtai.activity.ProjectDetailActivity;
import com.keyancompany.zhongbaopingtai.activity.ProjectMessageActivity;
import com.keyancompany.zhongbaopingtai.activity.SystemMessageActivity;
import com.keyancompany.zhongbaopingtai.adapter.MessageAdapter;
import com.keyancompany.zhongbaopingtai.api.FriendsAPI;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.FindModel;
import com.keyancompany.zhongbaopingtai.model.MessageModel;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import java.util.List;

import butterknife.Bind;
import butterknife.OnItemClick;

import static com.keyancompany.zhongbaopingtai.activity.ChatFriendActivity.BUNDLE_RES_INFO;

/**
 * Created by firefox on 2016/5/31.
 */
public class MessageFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {


    @Bind(R.id.listView)
    IListView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;

    private MessageAdapter messageAdapter;
    private int currentPage = 1, total = 1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeLayout.setRefreshing(false);
                    messageAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.fragment_message;
    }

    @Override
    public void setUpViews() {
        initSwipeLayout(swipeLayout);
        messageAdapter = new MessageAdapter(context);
        listView.setAdapter(messageAdapter);
        swipeLayout.setOnRefreshListener(this);

        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
//                requestTask(++currentPage);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        swipeLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        }));
    }

    public void requestTask() {

        FriendsAPI.getLetterList(currentPage, new IAsyncHttpResponseHandler() {

            @Override
            public void start(int type) {

            }

            @Override
            public void success(int type, String json) {
                //{result：返回状态（sucess：成功，error：失败）,token:验证,data:数据{"total":总页数,"current":当前页,
                // "list":[{"createtime":创建时间,"message":消息内容","username":发信人",
                // "toUser":收件人,"fromUser":接见人,"PID_":主键,"isread":是否阅读0否1是,
                // "isdelete":是否删除,"counts":2,"type":0系统消息，1项目信息，2个人消息}

                if (getActivity() == null) return;
                messageAdapter.clear();
                mHandler.sendEmptyMessage(1);
                if (type == FriendsAPI.LETTER_LIST) {
                    BaseModel base = JSONObject.parseObject(json, BaseModel.class);
                    Log.e("Message *** Fragment", " ---- " + base.toString());
                    if (base.isSuccess()) {
                        JSONObject object = JSONObject.parseObject(base.data);
                        currentPage = object.getInteger(Constants.CURRENT);
                        total = object.getInteger(Constants.TOTAL);
                        List<MessageModel> list = JSONObject.parseArray(object.getString("list"), MessageModel.class);
                        if (messageAdapter == null) return;
                        listView.loadMoreFinish();
                        if (total == currentPage) {
                            listView.removeFooterView();
                        }
                        messageAdapter.addAllAfter(list);
                        messageAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void failed(String error) {
                mHandler.sendEmptyMessage(1);
            }

            @Override
            public void finish(int type) {

            }
        }, null);
    }

    @OnItemClick(R.id.listView)
    void itemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < messageAdapter.getCount()) {
//            IntentUtils.startActivity(context, ChatActivity.class, Constants.CHAT_DETIAL, messageAdapter.getItem(position));
            //（0系统消息，1项目信息，2个人消息）
            messageAdapter.getItem(position).setIsread(1);
            if (messageAdapter.getItem(position).getType() == 0) {
                IntentUtils.startActivity(context, SystemMessageActivity.class, Constants.ITEM, messageAdapter.getItem(position));
            } else if (messageAdapter.getItem(position).getType() == 1) {
                IntentUtils.startActivity(context, ProjectMessageActivity.class, Constants.ITEM, messageAdapter.getItem(position));
            } else {
                Bundle bundle = new Bundle();
//                bundle.putString("res", BUNDLE_RES_INFO);
//                bundle.putSerializable(Constants.ITEM, messageAdapter.getItem(position));
//                bundle.putString("pid", messageAdapter.getItem(position).getPID_());
//                IntentUtils.startActivity(context, ChatFriendActivity.class, bundle);

                MessageModel messageModel = messageAdapter.getItem(position);
                bundle.putString("res", BUNDLE_RES_INFO);
                bundle.putString("userName", messageModel.getUsername());
                bundle.putString("pid", messageModel.getFromUser());
                IntentUtils.startActivity(context, ChatFriendActivity.class, bundle);
            }
        }
    }


    @Override
    public void onRefresh() {
        requestTask();
    }
}